package cn.fch.gotrip.filter;

/**
 * @program: gotrip
 * @description:
 * @CreatedBy: fch
 * @create: 2023-01-15 17:26
 **/
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter(
        value = "/*",
        initParams = @WebInitParam(name = "isCross", value = "true")
)
public class SimpleCorsFilter implements Filter {

    private boolean isCross = false;

    private final List<String> allowedOrigin = Arrays.asList("http://localhost:9528");

    @Override
    public void destroy() {
        isCross = false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (isCross) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;

            String origin = request.getHeader("Origin");

            // 设置跨域相关响应头数据内容
            response.setHeader("Access-Control-Allow-Origin", allowedOrigin.contains(origin) ? origin : "");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, userId, token");
            response.setHeader("Access-Control-Max-Age", "0");
            // 【允许跨域 Cookie 操作必要参数】
            response.setHeader("Access-Control-Allow-Credentials", "true");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("isCross");
        isCross = isCrossStr.equals("true");
    }
}